var common = require("../../common/utils.js");
var app = getApp();
var CryptoJS = require('../../common/tripledes.js');

//DES解密
function decryptByDES(ciphertext, key) {
  try {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    // direct decrypt ciphertext
    const decrypted = CryptoJS.DES.decrypt(ciphertext, keyHex, {
      iv: keyHex,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
  } catch (err) {
  }
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    appColor: app.appColor,
    show: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    array: ['身份证', '回乡证', '护照', '台胞证'], //下拉列表的数据
    index: 0,
    inputType: 'idcard',
    userCarid: "",
    userName: "",
    // takemanid: "",
    userPhone: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    try{
      wx.getStorage({
        key: '_userToken',
        success(res) {
          if (res.data.accesstoken) {
            that.getUserData(res.data.accesstoken);
            that.stanToken = res.data.accesstoken;
            app.accesstoken = res.data.accesstoken;
            if(res.data.HandsetNumber){
              that.setData({
                userPhone: res.data.HandsetNumber
              })
            }
          }
        },
        fail(err) {}
      })
    }catch(err){}
    if (options.reportId) {
      this.reportId = options.reportId;
    } else {
      this.reportId = decryptByDES(options.code, 'lwspsystem').split(",")[0];
    }
  },
  // 用户信息授权按钮  
  bindGetUserInfo(e) {
    try {
      let that = this;
      var user = e.detail;
      app.userinfo.nickname = user.userInfo.nickName ? user.userInfo.nickName : '';
      app.userinfo.headimg = user.userInfo.avatarUrl;
      that.putUserData(this.codes, user.iv, user.encryptedData);
    } catch (err) { }
  },

  bindPickerChange: function (e) {
    let val = e.detail.value;
    this.setData({
      index: val,
      inputType: val == '0' ? 'idcard' : 'text'
    })
  },
  // 调用微信用户信息接口
  userLogin: function () {
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          that.codes = res.code;
        }
      },
      fail: function () { }
    })
  },
  // 获取Token，如果用户授权，直接调用微信官方WX.getUserInfo方法获取用户信息，而不是弹框授权
  GetUserToken: function () {
    var that = this;
    // 通过 wx.getSetting 先查询一下用户是否授权了 "scope.record"
    try {
      wx.getSetting({
        success(res) {
          app.hideLoadings();
          if (res.authSetting['scope.userInfo']) {
            wx.login({
              success: function (res) {
                if (res.code) {
                  // 用户首次进入小程序时，如果检测到用户已经授权，则获取新的Token
                  wx.getUserInfo({
                    success(data) {
                      app.userinfo.nickname = data.userInfo.nickName ? data.userInfo.nickName : '';
                      app.userinfo.headimg = data.userInfo.avatarUrl;
                      that.putUserData(res.code, data.iv, data.encryptedData);
                      that.setData({
                        ModalSwitch: false
                      })
                    }
                  });
                }
              },
              fail: function (err) { }
            })
          } else {
            // 未授权的解决方案 ====  调用微信获取用户信息按钮
            that.userLogin();
            app.hideLoadings();
            that.setData({
              // 页面模态框开关
              // JS模态框开关
              ModalSwitch: true,
            })
          }
        },
        complete: () => {
          app.hideLoadings();
        }
      })
    } catch (err) { }
  },

  // 授权失败模态提示框
  shouquanFail: function (err) {
    wx.showModal({
      title: err,
      content: '服务器繁忙，请点击页面按钮重试',
      showCancel: false,
      success: function () {
        app.hideLoadings();
      }
    })
  },

  // 发送用户数据给后台
  putUserData: function (code, IV, EncryptedData) {
    app.hideLoadings();
    let that = this;
    // Token数据请求
    wx.request({
      url: app.serviceurl + 'GetToken',
      method: "POST",
      data: {
        code: code,
        options: JSON.stringify(app.o),
        IV: IV,
        EncryptedData: EncryptedData
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.AccessToken) {
          that.setData({
            ModalSwitch: false
          })
          let resData = res.data;
          if (resData.openId !== "") {
            app.optionsToken = resData.openId;
          }
          app.HandsetNumber = resData.HandsetNumber;
          app.IsRegister = resData.IsRegister;
          app.newUser = resData.IsNewUser;
          app.accesstoken = resData.AccessToken;
          // 是否为新用户
          app.IsFresh = resData.IsFresh;
          try {
            // 将用户数据存储进本地缓存
            wx.setStorage({
              key: '_userToken',
              data: {
                HandsetNumber: resData.HandsetNumber,
                IsRegister: resData.IsRegister,
                accesstoken: resData.AccessToken,
                userDate: new Date()
              },
            });
            // 疫情包车业务二维码页面
            if (that.yiqingCode && that.touser) {
              that.toUserList();
            }
          } catch (err) { }
        } else {
          that.shouquanFail(res.data.Message);
        }
      },
      fail: function () {
        try {
          that.shouquanFail(res.data.Message);
          app.hideLoadings();
        } catch (e) { }
      },
      complete: () => {
        app.hideLoadings();
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      // 第一次获取Token
    if (!app.accesstoken) {
      this.setData({
        ModalSwitch: true
      })
      this.GetUserToken();
    } else {
      this.getUserData();
      this.setData({
        ModalSwitch: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // 获取input值
  DName: function (e) {
    this.setData({
      userName: e.detail.value
    })
  },
  cardId: function (e) {
    this.setData({
      TakemanCardIDs: e.detail.value
    })
  },
  DPhone: function (e) {
    this.setData({
      userPhone: e.detail.value
    })
  },

  // 提示框
  repetition: function (message) {
    wx.showModal({
      content: message,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          console.log('确定')
        }
      }
    });
  },

  // 登记新用户
  amend: function (TakemanName, TakemanCardID, TakemanPhone) {
    let that = this;
    wx.request({
      url: app.serviceurl + 'Member/Register',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {
        name: TakemanName,
        cardId: TakemanCardID,
        phone: TakemanPhone ? TakemanPhone : "",
        reportId: that.reportId
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.Result == false) {
          that.repetition(res.data.Message);
          return
        } else {
          wx.showModal({
            content: res.data.Message,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack({});
                console.log('确定')
              }
            }
          });
        }
      },
      fail: function (error) {
        that.repetition('添加失败');
      }
    });
  },

  getUserData: function (token, p) {
    let that = this;
    wx.request({
      url: app.serviceurl + 'Member/GetRegister',
      header: {
        Authorization: "Bearer " + token
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.isReport) {
          let userData = res.data.historyTables;
          that.setData({
            userCarid: userData.cardId,
            userName: userData.name,
          });
          if(userData.phone != ""){
            that.setData({
              userPhone: userData.phone
            })
          }
        }

      },
      fail: function (error) {
        // that.repetition('添加失败');
      }
    });
  },


  save: function () {

    try {
      let phone = this.data.userPhone;
      // 如果用户输入手机号进行判断
      if (typeof (phone) !== 'undefined' && phone !== '') {
        if (!common.ChkUtil.isMobile(phone)) {
          this.repetition("请核实手机号是否正确");
          return
        }
      }else{
        this.repetition("请输入手机号");
        return
      }
      // // 姓名验证 --- 1-20字符
      // let RegName = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{1,20}$/;
      // 除身份证外，其它证件号的正则表达式并不完善，后台也有验证
      let hui = /^([A-Z]\d{6,11}(\(\w{1}\))?)$/;
      let tai = /^\d{8}|^\d{18}|^[a-zA-Z0-9]{10}$/;
      let hu = /^([a-zA-z]|[0-9]){5,17}$/;
      var TakemanName;
      var TakemanCardID;
      if (!this.data.TakemanCardIDs && !this.data.TakemanNames) {
        // 去空格
        TakemanName = this.data.userName.replace(/\s/g, "");
        TakemanCardID = this.data.userCarid.replace(/\s/g, "");
      } else {
        // 去空格
        TakemanName = this.data.TakemanNames ? this.data.TakemanNames.replace(/\s/g, "") : this.data.userName.replace(/\s/g, "");
        TakemanCardID = this.data.TakemanCardIDs ? this.data.TakemanCardIDs.replace(/\s/g, "") : this.data.userCarid.replace(/\s/g, "");
      }
      if (!TakemanCardID || !TakemanName) {
        this.repetition("请核实信息是否填正确");
        return
      }

      // 回乡证判断
      if (this.data.index == 1) {
        if (hui.test(TakemanCardID)) {
          this.amend(TakemanName, TakemanCardID, phone)
          return
        } else {
          this.repetition("请核对证件号是否正确");
        }
        return
      }
      // 护照判断
      if (this.data.index == 2) {
        if (hu.test(TakemanCardID)) {
          this.amend(TakemanName, TakemanCardID, phone)
          return
        } else {
          this.repetition("请核对证件号是否正确");
        }
        return
      }
      // 台胞证判断
      if (this.data.index == 3 && tai.test(TakemanCardID)) {
        if (tai.test(TakemanCardID)) {
          this.amend(TakemanName, TakemanCardID, phone)
          return
        } else {
          this.repetition("请核对证件号是否正确");
        }
        return
      }

      if (TakemanName && common.ChkUtil.isIdCardNew(TakemanCardID)) {
        // 所有验证通过
        this.amend(TakemanName, TakemanCardID, phone)
        // if (this.data.takemanid) {
        //   this.deleteUser(this.data.takemanid, TakemanName, TakemanCardID, phone)
        // } else {

        // }
      } else if (!TakemanName) {
        this.repetition("姓名需要2个中文以上")
      } else if (!common.ChkUtil.isIdCardNew(TakemanCardID)) {
        this.repetition("请确认这是正确的证件号")
      }
    } catch (err) {
      this.repetition('登记失败');
      console.log(err)
    }
  }


})